import ErrorComp from '@/components/common/error-comp';
import MessageBox from '@/components/common/message-box';
import AiSummary from '@/components/shop/ai-summary';
import IsInChat from '@/components/shop/is-in-chat';
import { Skeleton } from '@/components/ui/skeleton';
import { getSession } from '@/lib/auth';
import redis, { genInChatKey, genNewMessageButNotInChatKey } from '@/lib/redis';
import { messagesAiSummary } from '@/service/actions/message';
import { getMessages } from '@/service/query/message';
import { Suspense } from 'react';
import { z } from 'zod';

export const metadata = {
  title: '在线客服',
};

const paramSchema = z.object({
  id: z.string(),
});

export default async function Page({
  params,
}: { params: Promise<{ id: string }> }) {
  const paramsRes = paramSchema.safeParse(await params);
  if (!paramsRes.success)
    return <ErrorComp message="参数错误" backPath="/shop/message" />;

  const session = await getSession();
  if (!session?.user) return <ErrorComp message="用户未登录" />;

  const { result, error } = await getMessages({
    userId: paramsRes.data.id,
    shopUserId: session.user.id,
  });
  if (error)
    return <ErrorComp message={error.message} backPath="/shop/message" />;

  const setIsInChat = async (inChat: boolean) => {
    'use server';
    const key = genInChatKey({
      userId: paramsRes.data.id,
      shopUserId: session.user.id,
    });
    inChat ? redis.setEx(key, 60 * 30, '') : redis.del(key);
  };

  const newMessageButNotInChatKey = genNewMessageButNotInChatKey({
    userId: paramsRes.data.id,
    shopUserId: session.user.id,
  });

  const isNewMessageButNotInChat =
    (await redis.keys(newMessageButNotInChatKey))?.length > 0;

  const aiSummaryRes =
    isNewMessageButNotInChat &&
    messagesAiSummary({
      messages: result,
      redisKeyToDelete: newMessageButNotInChatKey,
    });

  return (
    <div className="max-w-[850px] mx-auto bg-background px-16 pt-5 min-h-[90vh] shadow-lg relative rounded-lg">
      <IsInChat setIsInChat={setIsInChat} />
      {aiSummaryRes && (
        <Suspense
          fallback={
            <div className="h-fit text-sm bg-background space-y-1 p-2 px-3 absolute max-w-[500px] w-full left-1/2 -translate-x-1/2 rounded-lg border">
              <div>AI 消息总结</div>
              <Skeleton className="h-8 w-full" />
            </div>
          }
        >
          <AiSummary aiSummaryRes={aiSummaryRes} />
        </Suspense>
      )}
      <MessageBox initMessages={result} toId={paramsRes.data.id} />
    </div>
  );
}
